package com.wx.dao.impl;

import com.wx.dao.BillDao;
import com.wx.domain.Bill;
import com.wx.utils.JDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.Objects;

/**
 * @author 27250
 */
public class BillDaoImpl implements BillDao {

    JdbcTemplate jdbcTemplate=new JdbcTemplate(JDBCUtils.getDataSource());

    @Override
    public List<Bill> findBillsByPatientId(String patientId) {
        return jdbcTemplate.query("select * from bill where patientId = ?",
                new BeanPropertyRowMapper<Bill>(Bill.class), patientId);
    }

    @Override
    public void paymentMoney(String billsId) {
        jdbcTemplate.update("update bill set payment = '已支付' where billId = ?",billsId);
    }

    @Override
    public List<Bill> findBillsByDoctorId(String doctorId) {
        return jdbcTemplate.query("select * from bill where doctorId = ?",
                new BeanPropertyRowMapper<Bill>(Bill.class), doctorId);
    }

    @Override
    public int addBill(Bill bill) {
        PreparedStatementCreator creator=new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                PreparedStatement preparedStatement=connection.prepareStatement("insert into `bill` values(?,?,?,?,?,?)",PreparedStatement.RETURN_GENERATED_KEYS);
                preparedStatement.setObject(1,null);
                preparedStatement.setInt(2, bill.getDoctorId());
                preparedStatement.setInt(3,bill.getPatientId());
                preparedStatement.setString(4,bill.getBillAll());
                preparedStatement.setDouble(5,bill.getMoney());
                preparedStatement.setString(6,bill.getPayment());
                return preparedStatement;
            }
        };

        GeneratedKeyHolder keyHolder=new GeneratedKeyHolder();

        jdbcTemplate.update(creator, keyHolder);

        //        jdbcTemplate.update("insert into sys_user values (null,?,?,?,?)",user.getUsername(),user.getEmail(),user.getPassword(),user.getPhoneNum());
        return Objects.requireNonNull(keyHolder.getKey()).intValue();
    }
}
